package com.study.thread.juc.lock;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class Semaphore1 {

    private Sync sync = new Sync();

    public void acquire(int count) {
        sync.acquireShared(count);
    }

    public void release() {
        sync.releaseShared(1);
    }

    public static class Sync extends AbstractQueuedSynchronizer {

        @Override
        protected int tryAcquireShared(int arg) {
            int state = getState();
            if (state == arg) {
                return 1;
            }
            return -1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            for (; ; ) {
                int state = getState();
                int stateC = state + arg;
                if (state == 0) {
                    return false;
                }
                if (compareAndSetState(state, stateC)) {
                    if (state > 0) {
                        return true;
                    }

                }
            }
        }

        @Override
        protected boolean isHeldExclusively() {
            return super.isHeldExclusively();
        }
    }
}
